<!DOCTYPE html>
<html>
<head>
    <title>JSON 解析测试</title>
</head>
<body>
    <h1>JSON 解析修复验证</h1>
    <button onclick="testJSONParsing()">测试 JSON 解析</button>
    <pre id="output"></pre>

    <script>
        function parseAIResponse(content) {
            if (!content) return null;
            
            let jsonContent = content.trim();
            
            // 移除可能的 Markdown 代码块
            if (jsonContent.startsWith('```json') && jsonContent.endsWith('```')) {
                jsonContent = jsonContent.replace(/^```json\s*/, '').replace(/\s*```$/, '');
            } else if (jsonContent.startsWith('```') && jsonContent.endsWith('```')) {
                jsonContent = jsonContent.replace(/^```[a-zA-Z]*\s*/, '').replace(/\s*```$/, '');
            }
            
            try {
                return JSON.parse(jsonContent.trim());
            } catch (error) {
                console.warn('JSON 解析失败，尝试提取 JSON 对象');
                const jsonMatch = jsonContent.match(/\{[\s\S]*\}/);
                if (jsonMatch) {
                    try {
                        return JSON.parse(jsonMatch[0]);
                    } catch (secondError) {
                        console.error('提取的 JSON 也无法解析');
                    }
                }
                return null;
            }
        }

        function testJSONParsing() {
            const testCases = [
                // 原始问题的响应
                `\`\`\`json
{
  "title": "A Day at the Community Learning Center",
  "description": "Test description",
  "imagePrompt": "Test prompt",
  "wordContexts": [
    {
      "word": "education",
      "contextDescription": "Test context",
      "position": {
        "x": 15,
        "y": 10
      }
    }
  ]
}
\`\`\``,
                // 普通 JSON
                `{
  "title": "Simple Test",
  "description": "Simple description"
}`,
                // 带额外文本的响应
                `Here is the JSON:
\`\`\`json
{
  "title": "With Extra Text",
  "description": "Has extra text"
}
\`\`\`
End of response.`
            ];

            const output = document.getElementById('output');
            let result = '';

            testCases.forEach((testCase, index) => {
                result += `测试用例 ${index + 1}:\n`;
                result += `输入: ${JSON.stringify(testCase)}\n`;
                
                try {
                    const parsed = parseAIResponse(testCase);
                    result += `结果: ${JSON.stringify(parsed, null, 2)}\n`;
                    result += `状态: ✅ 成功\n\n`;
                } catch (error) {
                    result += `错误: ${error.message}\n`;
                    result += `状态: ❌ 失败\n\n`;
                }
            });

            output.textContent = result;
        }
    </script>
</body>
</html>
